package com.ryf.maven.servlet.score;

import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;
import com.ryf.maven.dao.ScoreDao;
import com.ryf.maven.entity.BaseResponse;
import com.ryf.maven.entity.Score;
import com.ryf.maven.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description
 * @ClassName ScoreUpdateServlet
 * @Author L-Cohen
 * @date 2020.12.04 17:10
 */
@WebServlet(urlPatterns = "/score/update")
public class ScoreUpdateServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        Gson gson = new Gson();
        String scoreJson = RequestUtil.getRequestBody(req);

        Score scoreBody = gson.fromJson(scoreJson, Score.class);

        Score score = ScoreDao.getScore(scoreBody.getStuNo(), scoreBody.getCourseNo());
        if (!StringUtils.isNullOrEmpty(scoreBody.getStuName()) && !StringUtils.isNullOrEmpty(scoreBody.getCourseName())){
            score.setStuName(scoreBody.getStuName());
            score.setCourseName(scoreBody.getCourseName());
            score.setTerm(scoreBody.getTerm());
            score.setScore(scoreBody.getScore());
        }

        int rows = ScoreDao.updateScore(score);
        BaseResponse<Integer> baseResponse = new BaseResponse<Integer>();
        if (rows > 0)
        {
            baseResponse.setCode(200);
            baseResponse.setMsg("更新成功");
        }
        else
        {
            baseResponse.setCode(600);
            baseResponse.setMsg("更新失败");
        }
        baseResponse.setData(rows);


        String json = gson.toJson(baseResponse);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
    }
}
